// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//
//  IOSIntArray.m
//  JreEmulation
//
//  Created by Tom Ball on 6/16/11.
//

#import "IOSIntArray.h"
#import "IOSPrimitiveClass.h"
//#import "java/lang/Integer.h"

@implementation IOSIntArray

+ (id)arrayWithInts:(const int *)ints count:(NSUInteger)count {
  return [[[self alloc] initWithInts:ints
                               count:count] j2objc_autorelease];
}

- (id)initWithInts:(const int *)ints count:(NSUInteger)count {
  if ((self = [self initWithLength:count])) {
    if (NULL != ints) {
      memcpy(self.storage.mutableBytes, ints, self.storage.length);
    }
  }
  return self;
}

- (int)intAtIndex:(NSUInteger)index {
  [self checkIndex:index];
  
  const int *buffer = (const int *)self.storage.bytes;
  return buffer[index];
}

- (int)replaceIntAtIndex:(NSUInteger)index withInt:(int)i {
  [self checkIndex:index];
  
  int *buffer = (int *)self.storage.mutableBytes;
  buffer[index] = i;
  return i;
}

- (void)getInts:(int *)buffer length:(NSUInteger)length {
  [self checkIndex:(length - 1)];
  memcpy(buffer, self.storage.bytes, length * [[self class] elementLength]);
}

- (int)incr:(NSUInteger)index {
  [self checkIndex:index];
  
  int *buffer = (int *)self.storage.mutableBytes;
  return ++buffer[index];
}

- (int)decr:(NSUInteger)index {
  [self checkIndex:index];
  
  int *buffer = (int *)self.storage.mutableBytes;
  return --buffer[index];
}

- (int)postIncr:(NSUInteger)index {
  [self checkIndex:index];
  
  int *buffer = (int *)self.storage.mutableBytes;
  return buffer[index]++;
}

- (int)postDecr:(NSUInteger)index {
  [self checkIndex:index];
  
  int *buffer = (int *)self.storage.mutableBytes;
  return buffer[index]--;
}

- (NSString *)descriptionOfElementAtIndex:(NSUInteger)index {
  return [NSString stringWithFormat:@"%d", [self intAtIndex:index]];
}

- (IOSClass *)elementType {
  return [[[IOSPrimitiveClass alloc] initWithName:@"int"
                                             type:@"I"] j2objc_autorelease];
}

+ (NSUInteger)elementLength
{
  return sizeof(int);
}

@end
